<template>
  <div align="left">
    <h2>{{ title }}</h2>
    <p>发表于：{{ reportTime }}</p>
    <p>{{ icontent }}</p>
    <h3>读者回应</h3>
    <div v-for="(reply, index) in replies" :key="index" class="reply-item">
      <p>{{ reply.replyTime }}<br />{{ reply.rcontent }}</p>
    </div>
    <p>发表回复：(字数在200字以内)</p>
    <el-form :model="saveForm" :rules="rules" ref="saveForm">
      <el-form-item prop="content">
        <el-input
          id="content"
          type="textarea"
          v-model="saveForm.content"
        ></el-input>
      </el-form-item>
    </el-form>
    <button @click="doSave()">发表回复</button>
    <a href="#" @click="HotSpotConsultation()">返回首页</a>
  </div>
</template>

<script>
import qs from "qs";
export default {
  data() {
    return {
      id: this.$route.query.id,
      title: "",
      reportTime: "",
      icontent: "",
      replies: [], //存储回复时间、内容
      replyCount: 0,
      saveForm: {
        content: "",
        infoId: this.$route.query.id,
      },
      rules: {
        content: [
          {
            required: true,
            min: 1,
            max: 200,
            message: "必须填写回复内容，且字数不超过200！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.doSearch();
  },
  methods: {
    doSearch() {
      this.$axios
        .post("/hotSpotConsultation/content?id=" + this.id)
        .then((response) => {
          if (response.data.code == 0) {
            this.title = response.data.data[0].title;
            this.reportTime = response.data.data[0].reportTime;
            this.icontent = response.data.data[0].icontent;
            this.replyCount = response.data.data[0].replyCount; // 获取最新回复次数
            //将读者回复、时间存入到replies中
            this.replies = response.data.data.map((item) => ({
              replyTime: item.replyTime,
              rcontent: item.rcontent,
            }));
          }
        });
    },
    HotSpotConsultation() {
      this.$router.push({
        path: "/",
      });
    },
    doSave() {
      let queryStr = qs.parse(qs.stringify(this.saveForm));
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$axios
            .post("/hotSpotConsultation/add", queryStr)
            .then((response) => {
              if (response.data.code == 0) {
                this.saveForm.content = "";
                this.doSearch();
                this.$axios
                  .post("/hotSpotConsultation/update", {
                    replyCount: this.replyCount + 1,
                    id: this.id,
                  })
                  .then((response) => {
                    if (response.data.code == 0) {
                      this.doSearch();
                    }
                  });
                this.$message.success("发布成功！");
              }
            });
        }
      });
    },
  },
};
</script>

<style>
.reply-item {
  background-color: darkgray;
  border-radius: 4px;
}
</style>